function basePath(){
    var curWwwPath = window.document.location.href;
    var pathName =  window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0,pos);
    var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return (localhostPath + projectName);
}


loading();

$(function () {
    getDirections();
    getClassList(1);
    validatorU();
    validatorA();
    $("#add_class_btn").click(function () {
        add();
    });
    $("#update_class_btn").click(function () {
        update();
    });
    $("#list_btn").click(function () {
        var span_value = $("#list_span").html();
        if (span_value == "查看注销班级") {
            getLevelClassList(1);
            $("#list_btn").removeClass();
            $("#list_btn").addClass("btn btn-sm btn-info");
            $("#list_span").html("查看存在班级");
        } else {
            getClassList(1);
            $("#list_btn").removeClass();
            $("#list_btn").addClass("btn btn-sm btn-primary");
            $("#list_span").html("查看注销班级");
        }
    });


});


function validatorU() {
    $('#updateForm').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            newClassName: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '班级备注不能为空'
                    },
                    stringLength: {
                        min: 2,
                        max: 20,
                        message: '班级备注长度为2-20'
                    },
                    regexp: {
                        regexp: /^(?=[0-9a-zA-Z\u4e00-\u9fa5]+$)/,
                        message: '班级备注只能由中文，数字和英文字母组成'
                    },
                    different: {
                        field: '123',
                        message: '该备注已存在'
                    }
                }
            }
        }
    });
}

function validatorA() {
    $('#addForm').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            className1: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '班级名不能为空'
                    },
                    stringLength: {
                        min: 2,
                        max: 20,
                        message: '班级名长度为2-20'
                    },
                    regexp: {
                        regexp: /^(?=[0-9a-zA-Z\u4e00-\u9fa5]+$)/,
                        message: '班级名只能由中文，数字和英文字母组成'
                    }
                }
            },
            classContent: {
                messageL: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '班级备注不能为空'
                    },
                    stringLength: {
                        min: 2,
                        max: 20,
                        message: '班级备注长度为2-20'
                    },
                    regexp: {
                        regexp: /^(?=[0-9a-zA-Z\u4e00-\u9fa5]+$)/,
                        message: '备注只能由中文，数字和英文字母组成'
                    },
                    different: {
                        field: '123',
                        message: '该备注已存在'
                    }
                }
            }
        }
    });
}

var page_now = 1;
var this_page_num = 0;
var item_num = 10;

function getClassList(page_num) {
    page_now = page_num;
    $.ajax({
        url: basePath()+'/edu/class/class_list.do',
        type: 'GET',
        async: 'true',
        data: {
            "pageNum": page_num,
            "pageSize": "10"
        },
        dataType: 'json',
        success: function (data) {
            $('.alert').remove();
            $('#table').show();
            $('#pagination').show();
            removeLoading();
            var page = data.data;
            var item = data.data.list;
            this_page_num = item.length;
            setPage(page.pageNum, page.pages, "getClassList");
            $("#result").html("");
            for (var i = 0; i < item.length; i++) {
                var temp = $("#m_template").clone();
                temp.attr("id", item[i].id);
                temp.removeAttr("style");
                temp.find(".c_num").html(page.pageSize * (page.pageNum - 1) + 1 + i);
                temp.find(".c_name").html(item[i].name);
                temp.find(".c_content").html(item[i].other);
                temp.find(".c_type").html(item[i].direction);
                //修改按钮组装
                var up_btn = "<button type='button'  class='btn btn-primary btn-xs btn-warning' onclick='toModal(this);' ><span class='glyphicon glyphicon-edit' aria-hidden='true'></span><span style='margin: 0px 8px;'>修改</span></button>"
                temp.find(".c_update").html(up_btn);
                temp.find('.c_detail').html("<button type='button'  class='btn btn-primary btn-xs btn-info' onclick='toDetail("+item[i].id+");' style='margin-right: 10px;'><span class='glyphicon glyphicon-list-alt' aria-hidden='true'></span><span style='margin: 0px 8px;'>详情</span></button>");
                var op_btn = "<button type='button'  class='btn btn-primary btn-xs btn-danger' onclick='toChange(this);' ><span class='glyphicon glyphicon-remove' aria-hidden='true'></span><span style='margin: 0px 8px;'>过期</span></button>"
                temp.find(".c_op").html(op_btn);
                $("#result").append(temp);
            }
        }
    })
}

function getLevelClassList(page_num) {
    page_now = page_num;
    $.ajax({
        url: basePath()+'/edu/class/level_class_list.do',
        type: 'GET',
        async: 'false',
        data: {
            "pageNum": page_num,
            "pageSize": item_num
        },
        dataType: 'json',
        success: function (data) {
            var page = data.data;
            var item = data.data.list;
            setPage(page.pageNum, page.pages, "getLevelClassList");
            if (data.success) {
                if (data.data.list == "") {
                    $('#table').hide();
                    $('#pagination').hide();
                    $('#after_div').after("<div class='alert alert-warning alert-dismissible' role='alert'>\n" +
                        "  <button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>\n" +
                        "  <strong style='padding-left: 30px;'>暂时没有任何注销班级</strong>" +
                        "</div>");
                } else {
                    $('.alert').remove();
                    $('#table').show();
                    $('#pagination').show();
                    $("#result").html("");
                    for (var i = 0; i < item.length; i++) {
                        var temp = $("#m_template").clone();
                        temp.attr("id", item[i].id);
                        temp.removeAttr("style");
                        temp.find(".c_num").html(page.pageSize * (page.pageNum - 1) + 1 + i);
                        temp.find(".c_name").html(item[i].name);
                        temp.find(".c_content").html(item[i].other);
                        temp.find(".c_type").html(item[i].direction);
                        //修改按钮组装
                        temp.find(".c_update").html("<p class='label label-default'>不能修改</p>");
                        temp.find('.c_op').html("<p class='label label-default'>已注销</p>");
                        temp.find(".c_detail").html("<button type='button'  class='btn btn-info btn-xs' onclick='toDetail("+item[i].id+");' ><span class='glyphicon glyphicon-list-alt' aria-hidden='true'></span><span style='margin: 0px 8px;'>详情</span></button>");
                        $("#result").append(temp);
                    }
                }
            } else {
                bootbox.alert(data.msg);
            }
        }
    })
}

function add() {
    // 提交前先主动验证表单
    var bv = $("#addForm").data('bootstrapValidator');
    bv.validate();
    if (!bv.isValid()) {
        return;
    }
    var name = $("#className1").val();
    var content = $("#classContent").val();
    var c_type = $("#classDirection :selected").val();
    $.ajax({
        url: basePath()+'/edu/class/add_class.do',
        type: 'POST',
        async: 'true',
        data: {
            "name": name,
            "type": c_type,
            "other": content
        },
        dataType: 'json',
        success: function (res) {
            if (res.success) {
                clearAddModal();
                bootbox.alert(res.msg);
                if (this_page_num == item_num) {
                    getClassList(page_now + 1);
                } else {
                    getClassList(page_now);
                }

            } else {
                $('#addForm').data('bootstrapValidator').updateStatus('classContent', 'INVALID', 'different');
            }

        }
    });
}

function clearAddModal() {
    $('#addClass').modal('hide');
    $('#className1').val("");
    $('#classContent').val("");

    $('#addForm').data('bootstrapValidator').destroy();
    $('#addForm').data('bootstrapValidator', null);
    $("form[id='addForm'] > div").addClass('has-success');
    validatorA();
}

//更新备注
function update() {
    // 提交前先主动验证表单
    var bv = $("#updateForm").data('bootstrapValidator');
    bv.validate();
    if (!bv.isValid()) {
        return;
    }

    var new_content = $("#newClassName").val();
    var id = $("#hello").val();
    $.ajax({
        url: basePath()+'/edu/class/update_class_other.do',
        type: 'POST',
        async: 'true',
        data: {
            "other": new_content,
            "id": id
        },
        dataType: 'json',
        success: function (res) {
            if (!res.success) {
                $('#updateForm').data('bootstrapValidator').updateStatus('newClassName', 'INVALID', 'different');
            } else {
                bootbox.alert(res.msg);
                $('body').css('padding-right', '0px');
                clearUpdateModal();
                getClassList(page_now);
            }
        }
    })
}

function clearUpdateModal() {
    $('#changClass').modal('hide');
    $('#newClassName').val("");

    $('#updateForm').data('bootstrapValidator').destroy();
    $('#updateForm').data('bootstrapValidator', null);
    $("form[id='updateForm'] > div").addClass('has-success');
    validatorU();
}

function toModal(what) {
    var c_id = $(what).parent().parent().attr("id");
    console.log(c_id);
    $("#hello").val(c_id);
    $("#changClass").modal("show");
}

//注销班级
function toChange(what) {
    bootbox.confirm({
        message: "确认过期吗?",
        buttons: {
            confirm: {
                label: '<span class="glyphicon glyphicon-ok" aria-hidden="true"></span> 是',
                className: 'btn-danger'
            },
            cancel: {
                label: '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span> 否',
                className: 'btn-default'
            }
        },
        callback: function (result) {
            if (result) {
                var c_id = $(what).parent().parent().attr("id");
                $.ajax({
                    url: basePath()+'/edu/class/update_class_state.do',
                    method: 'POST',
                    async: 'true',
                    data: {
                        "id": c_id
                    },
                    dataType: 'json',
                    success: function (res) {
                        bootbox.alert(res.msg);
                        getClassList(1);
                    }
                })
            }
        }
    });
}

function toDetail(what) {
    window.location.href = basePath()+"/edu/class/get_class_details.do?id=" + what;
}

function getDirections() {
    var url = basePath()+"/edu/direction/get_all_directions.do";
    var data = "";
    $.get(url, data, function (data) {
        if (data.status == 0) {
            $("#classDirection").append("<option value='0'>全部</option>");
            for (var i = 0; i < data.data.length; i++) {
                $("#classDirection").append("<option value='" + data.data[i].id + "'>" + data.data[i].name + "</option>");
            }
        } else {
            bootbox.alert(data.msg);
        }
    }, "JSON");
}
